import Vue from 'vue'
import VueRouter from 'vue-router'

// import Login from '../views/Login.vue'
// import Desktop from '../views/Desktop.vue'
import Page from '../views/Page.vue'

Vue.use(VueRouter);

const routes = [
  // {
  //   path: '/',
  //   component: Login,
  // },
  // {
  //   path: '/login',
  //   component: Login,
  // },
  // {
  //   path: '/desktop',
  //   component: Desktop,
  //   children: [{
  //     path: '/desktop/*',
  //     component: null,
  //   }],
  // },
  {
    path: '/*',
    component: Page,
  },
]

const router = new VueRouter({
  routes,
  mode: 'history',
});

router.beforeEach((to, from, next) => {
  const loginToken = sessionStorage.getItem('LOGIN_TOKEN')
  // 处理租户ID
  let toPath = to.path
  const tenantId = toPath.substring(1)
  if (tenantId.length === 19 && tenantId.indexOf('/') === -1) {
    sessionStorage.setItem('TENANT_ID', tenantId)
    toPath = '/'
  } else if (tenantId.length === 0) {
    sessionStorage.removeItem('TENANT_ID')
  }
  if (toPath === '/') { // 访问首页
    if (loginToken) { // 已登录——>跳到系统主页
      next('/desktop')
    } else { // 未登录——>跳到登录页
      next('/login')
    }
  } else if (toPath.indexOf('/login') === 0) { // 访问登录页
    next()
  } else if (loginToken) { // 已经登录——>继续访问
    next();
  } else if (toPath.indexOf('/desktop') === 0) { // 未登录：不允许访问系统主页——>跳到登录页
    next('/login');
  } else { // 未登录：允许访问非系统主页
    next();
  }
});

export default router;
